<template>
  <div>
    <el-select
      v-model="value"
      @change="(v) => $emit('input', v)"
      placeholder="请选择"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      options: [],
    };
  },
  props: {
    dataSource: {
      type: Array,
      default: () => [],
    },
    filter: Function,
    value: String,
    defaultValue: String
  },
  model: {
    prop: "value",
    event: "input",
  },
  watch: {
    dataSource: function (v, o) {
      this.init();
    },
  },
  methods: {
    init() {
      let keys = new Set();
      let rej = new Set();
      this.dataSource.forEach((v) => {
        Object.keys(v).forEach((k) => {
          if (k in keys) {
            return;
          }
          if (k in rej) {
            return;
          }

          if (this.filter) {
            if (this.filter(k, v[k])) {
              keys.add(k);
            } else {
              rej.add(k);
            }
          } else {
            keys.add(k);
          }
        });
      });
      let opts = [];
      keys.forEach((k) => {
        opts.push({
          value: k,
          label: k,
        });
      });
      this.options = opts;
      if (this.defaultValue) {
          this.$emit("input", this.defaultValue);
      }
      else if (this.options.length > 0) {
        
        console.log(this.options[0].value);
        this.$emit("input", this.options[0].value);
      }

      // this.value = this.options[0].value
    },
  },
  mounted() {
    this.init();
  },
};
</script>

<style>
</style>